package com.sy.simpleegg.platform.kkb.manager

import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.platform.kkb.bean.login.GetRegisterNumData
import com.sy.simpleegg.platform.kkb.bean.login.LoginToken
import com.sy.simpleegg.platform.kkb.bean.login.RegisterData
import com.sy.simpleegg.platform.kkb.loader.InitApiLoader
import com.sy.simpleegg.platform.kkb.network.base.BaseResult
import com.sy.simpleegg.platform.kkb.signUtil.SignUtil
import com.sy.simpleegg.util.DateTimeUtil
import com.sy.simpleegg.util.GsonUtil
import io.reactivex.Observer
import io.reactivex.disposables.Disposable

class KkbInitApiManager {

//    companion object {
//        var instance: IBusinessManager? = null
//    }

    private val initApiLoader: InitApiLoader = InitApiLoader()

    private var isDebug = false

    private var useTestUrl = false

    private val key = "C5D7C9FD354349B1A23D1DEE318D4E58"

    private var applicationId: String = ""
    private var appVer: String = ""
    private var DevNum: String = ""
    private var MacID: String = ""
    private var netIp: String = ""
    private var netMask: String = ""
    private var netGateWay: String = ""


    private var showNum: String? = null

    private var regData: RegisterData? = null
    private var loginToken: LoginToken? = null

    private var initListener: InitListener? = null

    companion object {
        private var instance: KkbInitApiManager? = null
            get() {
                if (field == null) {
                    field = KkbInitApiManager()
                }
                return field
            }
        @Synchronized
        fun get(): KkbInitApiManager{
            return instance!!
        }
    }

    fun initApi(appVer: Int, netIp: String, netMask: String, netGateWay: String, devNum: String, macId: String, listener: InitListener){
        this.appVer = appVer.toString()
        this.netIp = netIp
        this.netMask = netMask
        this.netGateWay = netGateWay

        DevNum = devNum
        MacID = macId
        initListener = listener
        connectTest()
    }

    private fun connectTest(){
        initApiLoader.connectTest(object : Observer<BaseResult<Any?>>{
            override fun onSubscribe(d: Disposable) {

            }

            override fun onError(e: Throwable) {
                logFile("KKB 连接测试异常：${e.message}")
            }

            override fun onComplete() {
                logFile("KKB 连接测试结束")
                getRegistNum()
            }

            override fun onNext(t: BaseResult<Any?>) {
                logFile("KKB 连接测试完成：${GsonUtil.getInstance()?.toJson(t)}")
            }
        })
    }

    private fun getRegistNum(){
        val sign = SignUtil.getSige(mapOf(
            Pair("MacID", MacID),
            Pair("PayDeviceType", "3"),
            Pair("TS", DateTimeUtil.timeStampS),
            Pair("HardNum", "0"),
            Pair("CoinELevel", "1"),
            Pair("TicketELevel", "1"),
            Pair("TicketEyeELevel", "1"),
            Pair("NetIP", netIp),
            Pair("NetMask", netMask),
            Pair("NetGateWay", netGateWay),
            Pair("BusinessNum", ""),
        ), key)

        val map: Map<String?, Any> = mapOf(
            Pair("MacID", MacID),
            Pair("PayDeviceType", "3"),
            Pair("Sign", sign?:""),
            Pair("TS", DateTimeUtil.timeStampS),
            Pair("HardNum", "0"),
            Pair("CoinELevel", "1"),
            Pair("TicketELevel", "1"),
            Pair("TicketEyeELevel", "1"),
            Pair("NetIP", netIp),
            Pair("NetMask", netMask),
            Pair("NetGateWay", netGateWay),
            Pair("BusinessNum", ""),
        )
        initApiLoader.getRegistNum(map, object : Observer<BaseResult<GetRegisterNumData?>>{
            override fun onSubscribe(d: Disposable) {

            }

            override fun onError(e: Throwable) {
                logFile("KKB 申请临时注册号异常：${e.message}")
            }

            override fun onComplete() {
                logFile("KKB 申请临时注册号结束")
                showNum?.let {
                    preRegist(it)
                }
            }

            override fun onNext(t: BaseResult<GetRegisterNumData?>) {
                logFile("KKB 申请临时注册号完成：${GsonUtil.getInstance()?.toJson(t)}")
                showNum = t.data?.ShowNum?:""
            }
        })
    }

    private fun preRegist(regNumber: String){
        val sign = SignUtil.getSige(mapOf(
            Pair("MacID", MacID),
            Pair("ShowNum", regNumber),
            Pair("PayDeviceType", "3"),
            Pair("TS", DateTimeUtil.timeStampS),
        ), key)

        val map: Map<String?, Any> = mapOf(
            Pair("MacID", MacID),
            Pair("ShowNum", regNumber),
            Pair("PayDeviceType", "3"),
            Pair("Sign", sign?:""),
            Pair("TS", DateTimeUtil.timeStampS),
        )
        initApiLoader.preRegist(map, object : Observer<BaseResult<RegisterData?>>{
            override fun onSubscribe(d: Disposable) {

            }

            override fun onError(e: Throwable) {
                logFile("KKB 预注册异常：${e.message}")
            }

            override fun onComplete() {
                logFile("KKB 预注册结束")
                regData?.let {
                    if (it.IsReg){
                        loginToken(MacID, DevNum, it.AppID, it.Key)
                    }
                }
            }

            override fun onNext(t: BaseResult<RegisterData?>) {
                logFile("KKB 预注册完成：${GsonUtil.getInstance()?.toJson(t)}")
                regData = t.data
            }
        })
    }

    private fun loginToken(macId: String, devNum: String, appId: String, key: String){
        val sign = SignUtil.getSige(mapOf(
            Pair("AppID", appId),
            Pair("MacID", macId),
            Pair("AppVer", appVer),
            Pair("HardVer", "1"),
            Pair("TS", DateTimeUtil.timeStampS),
            Pair("DevNum", devNum),
        ), key)
        logFile("loginToken sign = $sign")

        val map: Map<String?, Any> = mapOf(
            Pair("AppID", appId),
            Pair("MacID", macId),
            Pair("Sign", sign?:""),
            Pair("AppVer", appVer),
            Pair("HardVer", "1"),
            Pair("TS", DateTimeUtil.timeStampS),
            Pair("DevNum", devNum),
        )
        logFile("loginToken map = ${GsonUtil.getInstance()?.toJson(map)}")

        initApiLoader.loginToken(map, object : Observer<BaseResult<LoginToken?>>{
            override fun onSubscribe(d: Disposable) {

            }

            override fun onError(e: Throwable) {
                logFile("KKB 登录获取token异常：${e.message}")
            }

            override fun onComplete() {
                logFile("KKB 登录获取token结束")
                loginToken?.let {
                    initListener?.loginTokenData(it)
                }
            }

            override fun onNext(t: BaseResult<LoginToken?>) {
                logFile("KKB 登录获取token完成：${GsonUtil.getInstance()?.toJson(t)}")
                loginToken = t.data
            }
        })
    }

    interface InitListener{
        fun loginTokenData(loginToken: LoginToken)
    }

}